package com.irdstudio.apicenter.console.controller.template;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.irdstudio.apicenter.console.controller.MacmsBaseAction;
import com.irdstudio.apicenter.console.dm.util.FootPage;
import com.irdstudio.apicenter.console.dm.util.FootPageDao;
import com.irdstudio.apicenter.console.util.MacmsPathUtil;
import com.irdstudio.apicenter.frame.core.jdbc.JdbcBaseDAO;
import com.irdstudio.apicenter.frame.core.jdbc.container.PageInfo;
import com.irdstudio.apicenter.frame.maker.dm.STemplateBase;
import com.irdstudio.apicenter.frame.util.BeanUtils;

/**
 * 模板管理操作
 * 
 * @author zs.ligm
 * @version 1.0
 * @date 2015-06-26
 */
@Controller
@RequestMapping(value = "/template")
public class TemplateManagerAction extends MacmsBaseAction {

	/**
	 * 模板列表
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "queryList")
	public String queryList(HttpServletRequest request) throws Exception {
		String templateid = "";
		String templatename = "";
		if (request.getParameter("templateid") != null) {
			templateid = request.getParameter("templateid");
		}
		if (request.getParameter("templatename") != null) {
			templatename = request.getParameter("templatename");
		}

		// 取得传入应用标识
		String typeId = request.getParameter("type");
		if (StringUtils.isEmpty(typeId)) {
			throw new Exception("必须传入应用标识(appid)参数!");
		}

		int row = 0;
		int size = 0;
		row = (null == request.getParameter("pageNo") ? 0 : Integer
				.parseInt(request.getParameter("pageNo")));
		size = (null == request.getParameter("pageSize") ? 0 : Integer
				.parseInt(request.getParameter("pageSize")));

		// 获取分页参数信息
		// PageInfo pageInfo = super.getPageInfo();
		FootPage fp = new FootPage();
		FootPageDao fpd = new FootPageDao();
		fp = fpd.querypage("  s_template_base where template_type= '" + typeId
				+ "' and TEMPLATE_ID  like '%" + templateid
				+ "%'  and  TEMPLATE_NAME  like  '%" + templatename + "%'",
				row, size);
		row = (fp.getPageNo() - 1) * fp.getPageSize();
		// 查询数据并放入到上下文中
		String sql = "select * from s_template_base where template_type='"
				+ typeId + "' and TEMPLATE_ID  like '%" + templateid
				+ "%'  and  TEMPLATE_NAME  like  '%" + templatename + "%'";
		PageInfo pageInfo = new PageInfo();
		super.context.addDataList("stbList", this.getTableModelDAO().queryList(
				sql, pageInfo, null));
		super.context.addPageInfo("stbList", pageInfo);

		// 将数据上下文放到属性中
		request.setAttribute("context", super.context);
		request.setAttribute("type", typeId);
		request.setAttribute("page", fp);
		return "admin/templateList";
	}

	/**
	 * 模板创建
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "create")
	public String create(HttpServletRequest request) throws Exception {
		String type = request.getParameter("type");
		request.setAttribute("type", type);
		return "admin/templateCreate";
	}

	/**
	 * 保存模板
	 * 
	 * @param sTemplateBase
	 * @param request
	 * @param response
	 * @throws SQLException
	 * @throws ClassNotFoundException
	 */
	@RequestMapping(value = "saveTemplate")
	public void saveSTemplateBase(
			@ModelAttribute("sTemplateBase") STemplateBase sTemplateBase,
			HttpServletRequest request, HttpServletResponse response)
			throws SQLException, ClassNotFoundException {
		int flag = -1;

		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		String dateString = formatter.format(currentTime);
		sTemplateBase.setLastModifyDate(dateString);

		String sql = "insert into s_template_base  values(?,?,?,?,?)";
		JdbcBaseDAO baseDao = BeanUtils.getBean(JdbcBaseDAO.class);
		System.out.println("---"+sTemplateBase.getTemplateId()+"--"+sTemplateBase.getTemplateName()+"--"+sTemplateBase
				.getTemplateType()+"--"+sTemplateBase.getLastModifyDate()+"--"+sTemplateBase.getLongDesc());
		flag = baseDao.insert(sql, sTemplateBase.getTemplateId(), sTemplateBase
				.getTemplateName(), sTemplateBase.getTemplateType(),
				sTemplateBase.getLastModifyDate(), sTemplateBase.getLongDesc());
		Map<String, Object> map = new HashMap<String, Object>(1);
		map.put("flag", flag);
		String jsonResult = JSON.toJSONString(map);
		PrintWriter printWriter = null;
		try {
			printWriter = response.getWriter();
			printWriter.print(jsonResult);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (null != printWriter) {
				printWriter.flush();
				printWriter.close();
			}
		}

	}

	/**
	 * 保存模板
	 * 
	 * @param sTemplateBase
	 * @param request
	 * @param response
	 * @throws SQLException
	 * @throws ClassNotFoundException
	 */
	@RequestMapping(value = "updateSTemplateBase")
	public void updateSTemplateBase(
			@ModelAttribute("sTemplateBase") STemplateBase sTemplateBase,
			HttpServletRequest request, HttpServletResponse response)
			throws SQLException, ClassNotFoundException {
		int flag = -1;

		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		String dateString = formatter.format(currentTime);
		sTemplateBase.setLastModifyDate(dateString);

		String sql = "update s_template_base  set  TEMPLATE_NAME=?,LAST_MODIFY_DATE=?,LONG_DESC=?   where TEMPLATE_ID=? ";
		JdbcBaseDAO baseDao = BeanUtils.getBean(JdbcBaseDAO.class);
		flag = baseDao.update(sql, sTemplateBase.getTemplateName(),
				sTemplateBase.getLastModifyDate(), sTemplateBase.getLongDesc(),
				sTemplateBase.getTemplateId());
		Map<String, Object> map = new HashMap<String, Object>(1);
		map.put("flag", flag);
		String jsonResult = JSON.toJSONString(map);
		PrintWriter printWriter = null;
		try {
			printWriter = response.getWriter();
			printWriter.print(jsonResult);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (null != printWriter) {
				printWriter.flush();
				printWriter.close();
			}
		}

	}

	/**
	 * 保存模板
	 * 
	 * @param sTemplateBase
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "deleteSTemplateBase")
	public void deleteSTemplateBase(
			@ModelAttribute("sTemplateBase") STemplateBase sTemplateBase,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		int flag = -1;

		// 取得传入模板标识
		String templateId = request.getParameter("template_id");
		if (StringUtils.isEmpty(templateId)) {
			throw new Exception("必须传入模板标识(template_id)参数!");
		}
		String sql = "delete  from  s_template_base  where  TEMPLATE_ID=?";
		String sql1 = "delete  from s_template_file  where  TEMPLATE_ID=?";
		String sql2 = "delete  from s_template_param where  TEMPLATE_ID=?";
		JdbcBaseDAO baseDao = BeanUtils.getBean(JdbcBaseDAO.class);
		flag = baseDao.delete(sql2, templateId);
		flag = baseDao.delete(sql1, templateId);
		flag = baseDao.delete(sql, templateId);
		Map<String, Object> map = new HashMap<String, Object>(1);
		map.put("flag", flag);
		String jsonResult = JSON.toJSONString(map);
		PrintWriter printWriter = null;
		try {
			printWriter = response.getWriter();
			printWriter.print(jsonResult);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (null != printWriter) {
				printWriter.flush();
				printWriter.close();
			}
		}

	}

	/**
	 * 模板编辑
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "edit")
	public String edit(HttpServletRequest request) throws Exception {

		// 取得传入模板标识
		String templateId = request.getParameter("template_id");
		if (StringUtils.isEmpty(templateId)) {
			throw new Exception("必须传入模板标识(template_id)参数!");
		}

		// 查询数据并放入到上下文中
		JdbcBaseDAO baseDao = BeanUtils.getBean(JdbcBaseDAO.class);
		STemplateBase template = baseDao.findBean(STemplateBase.class,
				new Object[] { templateId });

		// 将数据上下文放到属性中
		request.setAttribute("STemplateBase", template);

		// 将数据上下文放到属性中
		request.setAttribute("templateId", templateId);

		return "admin/templateEdit";
	}

	/**
	 * 模板基本信息编辑
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "baseInfoEdit")
	public String baseInfoEdit(HttpServletRequest request) throws Exception {

		// 取得传入模板标识
		String templateId = request.getParameter("template_id");
		if (StringUtils.isEmpty(templateId)) {
			throw new Exception("必须传入模板标识(template_id)参数!");
		}

		// 查询数据并放入到上下文中
		JdbcBaseDAO baseDao = BeanUtils.getBean(JdbcBaseDAO.class);
		STemplateBase template = baseDao.findBean(STemplateBase.class,
				new Object[] { templateId });

		// 将数据上下文放到属性中
		request.setAttribute("STemplateBase", template);

		return "admin/templateBaseInfoEdit";
	}

	/**
	 * 模板样图
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "samplePicture")
	public String samplePicture(HttpServletRequest request) throws Exception {

		// 取得传入模板标识
		String templateId = request.getParameter("template_id");
		if (StringUtils.isEmpty(templateId)) {
			throw new Exception("必须传入模板标识(template_id)参数!");
		}

		// 将数据上下文放到属性中
		request.setAttribute("templateId", templateId);

		return "admin/templateSamplePicture";
	}

	/**
	 * 模板文件列表
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "fileList")
	public String fileList(HttpServletRequest request) throws Exception {

		// 获取所有参数
		super.getAllRequestData(request);
		// 取得传入模板标识
		String templateId = request.getParameter("template_id");
		if (StringUtils.isEmpty(templateId)) {
			throw new Exception("必须传入模板标识(template_id)参数!");
		}
		//添加和删除按钮是否显示  0-显示   1-隐藏     默认0
		String flag = request.getParameter("flag");
		if(flag == null || "".equals(flag)){
			flag = "0";
		}

		// 查询数据并放入到上下文中
		String sql = "select * from s_template_file where template_id=?";
		super.context.addDataList("stfList", this.getTableModelDAO().queryList(
				sql, new PageInfo(), new Object[] { templateId }));

		// 将数据上下文放到属性中
		request.setAttribute("context", super.context);
		request.setAttribute("templateId", templateId);
		request.setAttribute("flag", flag);
		return "admin/templateFileList";
	}

	@RequestMapping(value = "uploadPic")
	public String uploadPic(HttpServletRequest request) throws Exception {
		String templateId = request.getParameter("templateId");
		request.setAttribute("templateId", templateId);
		return "admin/templatePicUpload";
	}

	@RequestMapping(value = "createfile")
	public String createfile(HttpServletRequest request) throws Exception {
		String templateId = request.getParameter("templateId");
		request.setAttribute("templateId", templateId);
		return "admin/templateFileAdd";
	}

	@RequestMapping(value = "deletefile")
	public void deletefile(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		int flag = -1;

		String templateId = request.getParameter("templateId");
		String templatefile = request.getParameter("templatefile");
		String sql = "delete  from s_template_file  where  TEMPLATE_ID=?  and  TEMPLATE_FILE=?";
		JdbcBaseDAO baseDao = BeanUtils.getBean(JdbcBaseDAO.class);
		flag = baseDao.delete(sql, templateId, templatefile);
		// 删除文件
		String FILE_PATH = MacmsPathUtil.mkdirFile("template", templateId);
		MacmsPathUtil.deleteFile(FILE_PATH + "/" + templatefile);
		// 返回前台
		Map<String, Object> map = new HashMap<String, Object>(1);
		map.put("flag", flag);
		String jsonResult = JSON.toJSONString(map);
		PrintWriter printWriter = null;
		try {
			printWriter = response.getWriter();
			printWriter.print(jsonResult);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (null != printWriter) {
				printWriter.flush();
				printWriter.close();
			}
		}

	}

	/**
	 * 模板参数列表
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "paramList")
	public String paramList(HttpServletRequest request) throws Exception {

		// 取得传入模板标识
		String templateId = request.getParameter("template_id");
		if (StringUtils.isEmpty(templateId)) {
			throw new Exception("必须传入模板标识(template_id)参数!");
		}

		// 查询数据并放入到上下文中
		String sql = "select * from s_template_param where template_id=? order by param_sort";
		super.context.addDataList("stpList", this.getTableModelDAO().queryList(
				sql, new PageInfo(), new Object[] { templateId }));

		// 将数据上下文放到属性中
		request.setAttribute("context", super.context);
		request.setAttribute("templateid", templateId);

		return "admin/templateParamList";
	}

}
